package com.baomidou.ant.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.PinLibrary;
import com.baomidou.ant.entity.ProcessCondition;
import com.baomidou.ant.service.IPinLibraryService;
import com.baomidou.ant.service.IProcessConditionService;
import com.baomidou.ant.vo.request.RequestAddMouldVo;
import com.baomidou.ant.vo.request.RequestConditionListVo;
import com.baomidou.ant.vo.response.ResponseConditionListVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/process-condition")
public class ProcessConditionController {
    @Autowired
    private IProcessConditionService processConditionService;
    @Autowired
    private IPinLibraryService pinLibraryService;
    @Value("${file.pathName}")
    private String path;
    @Value("${file.viewPath}")
    private String viewPath;

    @PostMapping("/listCondition")
    public Result listCondition(@RequestBody RequestConditionListVo vo){
        IPage<ResponseConditionListVo> iPage=processConditionService.listCondition(vo);
        return Result.getSuccess().setData(iPage);
    }

    @PostMapping("/addMould")
    public Result addMould(@RequestBody RequestAddMouldVo vo){
        QueryWrapper<ProcessCondition> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("pin_id",vo.getPinId());
        queryWrapper.eq("mould_status",1);
        if(processConditionService.getOne(queryWrapper)!=null){
            return Result.getFailure().setMsg("新增失败!</br>该产品已有在用模板!");
        }
        if(processConditionService.addMould(vo)){
            return Result.getSuccess().setMsg("新增成功</br>新增模板信息后,请回到管理页上传模板文件,否则无法使用");
        }else
            return Result.getFailure().setMsg("新增失败");
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Result uploadFile(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception  {
        //得到前端传来的参数
        Integer id= Integer.parseInt(request.getParameter("id"));
        ProcessCondition processCondition=processConditionService.getById(id);
        PinLibrary pinLibrary=pinLibraryService.getById(processCondition.getPinId());
        String issueAffix = null;
        if (file != null && !file.isEmpty()){
            if ((issueAffix = handleFormUpload(file,pinLibrary.getPinName())) != null) {
                System.err.println("文件,上传成功!");
                if(updateFileInfo(processCondition,issueAffix)){
                    return Result.getSuccess().setMsg("模板上传成功!绑定成功");
                }else
                    return Result.getSuccess().setMsg("模板上传成功,但绑定失败，请联系管理员!");
            } else if(Objects.equals(handleFormUpload(file,processCondition.getMouldKey()), "exist")) {
                System.err.println("文件,上传失败!");
                return Result.getFailure().setMsg("上传失败,文件名重复!");
            }else{
                System.err.println("文件,上传失败!");
                return Result.getFailure().setMsg("上传失败!");
            }
        }else
            return Result.getFailure().setMsg("文件为空");
    }
    /**
     * 文件上传
     * @param uploadfile
     */
    public String handleFormUpload(MultipartFile uploadfile,String pinName) throws Exception{
        // 获取上传文件的原始名称
        String originalFilename = uploadfile.getOriginalFilename();
        String[] filename = originalFilename.split("\\.");
        //临时文件
        File file=File.createTempFile(filename[0], "."+filename[1]);
        uploadfile.transferTo(file);
        //重命名,模板文件名为产品名
        file = FileUtil.rename(file, pinName, true, true);
        InputStream inputStream = new FileInputStream(file);
        //File转换成MultipartFile
        uploadfile = new MockMultipartFile(file.getName(), inputStream);
        //程序退出后删除临时文件
        file.deleteOnExit();
        if (!uploadfile.isEmpty()) {
            // 设置上传文件的保存地址目录
            String dirPath = path;
            File setFilePath = new File(dirPath);
            // 如果保存文件的地址不存在，就先创建目录
            if (!setFilePath.exists()) {
                setFilePath.mkdirs();
            }
            try {
                // 文件保存路径
                String filePath = dirPath + uploadfile.getName();
                // 转存文件
                uploadfile.transferTo(new File(filePath));
                return filePath;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    //上传文件后update
    public boolean updateFileInfo(ProcessCondition processCondition,String mouldPath){
        processCondition.setMouldPath(mouldPath);
        processCondition.setMouldStatus("1");
        return processConditionService.updateById(processCondition);
    }

    //停用模板
    @GetMapping("/banMould/{mouldId}")
    public Result banMould(@PathVariable Integer mouldId){
        ProcessCondition processCondition=processConditionService.getById(mouldId);
        if(Objects.equals(processCondition.getMouldStatus(), "1")){
            processCondition.setMouldStatus("2");
            if(processConditionService.updateById(processCondition)){
                return Result.getSuccess().setMsg("停用成功");
            }else
                return Result.getFailure().setMsg("停用失败");
        }else if(Objects.equals(processCondition.getMouldStatus(), "2")){
            processCondition.setMouldStatus("1");
            if(processConditionService.updateById(processCondition)){
                return Result.getSuccess().setMsg("启用成功");
            }else
                return Result.getFailure().setMsg("启用失败");
        }else
            return Result.getFailure().setMsg("该模板文件未绑定，无需禁用!");

    }

    //获取文件路径，预览接口
    @GetMapping("/getMouldPath/{mouldId}")
    public Result getMouldPath(@PathVariable Integer mouldId){
        ProcessCondition condition=processConditionService.getById(mouldId);
        String[] str=condition.getMouldPath().split("/");
        String fileName=str[str.length-1];
        String resultPath=viewPath+fileName;
        return Result.getSuccess().setData(resultPath);
    }

}
